package cn.edu.zime.tjh.gui;

import cn.edu.zime.tjh.client.AsyncEchoClient;
import javafx.application.Application;
import javafx.application.Platform;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.*;
import javafx.scene.layout.*;
import javafx.stage.Stage;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

public class ClientGUIApp extends Application {
    private TextArea messageArea;
    private TextField inputField;
    private Button connectButton;
    private Button disconnectButton;
    private Button sendButton;
    private TextField hostField;
    private TextField portField;
    private Label statusLabel;
    
    private AsyncEchoClient client;
    private boolean isConnected = false;
    
    @Override
    public void start(Stage primaryStage) {
        primaryStage.setTitle("IoT Communication Client");
        
        // 创建UI组件
        createUI(primaryStage);
        
        // 设置事件处理
        setupEventHandlers();
        
        primaryStage.setOnCloseRequest(e -> {
            disconnect();
            Platform.exit();
        });
        
        primaryStage.show();
    }
    
    private void createUI(Stage primaryStage) {
        VBox root = new VBox(10);
        root.setPadding(new Insets(10));
        
        // 连接配置区域
        HBox connectionBox = new HBox(10);
        connectionBox.getChildren().addAll(
            new Label("主机:"),
            hostField = new TextField("localhost"),
            new Label("端口:"),
            portField = new TextField("8080"),
            connectButton = new Button("连接"),
            disconnectButton = new Button("断开连接")
        );
        
        hostField.setPrefWidth(120);
        portField.setPrefWidth(80);
        disconnectButton.setDisable(true);
        
        // 状态标签
        statusLabel = new Label("状态: 未连接");
        statusLabel.setStyle("-fx-text-fill: red;");
        
        // 消息显示区域
        messageArea = new TextArea();
        messageArea.setEditable(false);
        messageArea.setPrefRowCount(20);
        messageArea.setWrapText(true);
        
        // 消息输入区域
        HBox inputBox = new HBox(10);
        inputField = new TextField();
        sendButton = new Button("发送");
        sendButton.setDisable(true);
        
        inputField.setPrefWidth(400);
        inputBox.getChildren().addAll(inputField, sendButton);
        
        // 组装界面
        root.getChildren().addAll(
            connectionBox,
            statusLabel,
            new Label("消息:"),
            messageArea,
            new Label("输入:"),
            inputBox
        );
        
        Scene scene = new Scene(root, 600, 500);
        primaryStage.setScene(scene);
    }
    
    private void setupEventHandlers() {
        connectButton.setOnAction(e -> connect());
        disconnectButton.setOnAction(e -> disconnect());
        sendButton.setOnAction(e -> sendMessage());
        
        inputField.setOnAction(e -> sendMessage());
    }
    
    private void connect() {
        String host = hostField.getText().trim();
        String portText = portField.getText().trim();
        
        if (host.isEmpty() || portText.isEmpty()) {
            showMessage("请输入主机和端口", "错误");
            return;
        }
        
        try {
            int port = Integer.parseInt(portText);
            
            // 创建异步客户端
            client = new AsyncEchoClient(
                this::handleReceivedMessage,
                this::handleStatusMessage
            );
            
            // 在新线程中连接
            new Thread(() -> {
                try {
                    client.connect(host, port);
                    
                    Platform.runLater(() -> {
                        isConnected = true;
                        connectButton.setDisable(true);
                        disconnectButton.setDisable(false);
                        sendButton.setDisable(false);
                        hostField.setDisable(true);
                        portField.setDisable(true);
                        statusLabel.setText("状态: 已连接到 " + host + ":" + port);
                        statusLabel.setStyle("-fx-text-fill: green;");
                        showMessage("已连接到服务器", "系统");
                    });
                    
                    // 等待连接断开
                    client.waitForDisconnection();
                    
                } catch (Exception ex) {
                    Platform.runLater(() -> {
                        showMessage("连接失败: " + ex.getMessage(), "错误");
                        resetConnectionState();
                    });
                }
            }).start();
            
        } catch (NumberFormatException ex) {
            showMessage("无效的端口号", "错误");
        }
    }
    
    private void disconnect() {
        if (client != null) {
            client.disconnect();
        }
        resetConnectionState();
    }
    
    private void resetConnectionState() {
        Platform.runLater(() -> {
            isConnected = false;
            connectButton.setDisable(false);
            disconnectButton.setDisable(true);
            sendButton.setDisable(true);
            hostField.setDisable(false);
            portField.setDisable(false);
            statusLabel.setText("状态: 未连接");
            statusLabel.setStyle("-fx-text-fill: red;");
            showMessage("已断开与服务器的连接", "系统");
        });
    }
    
    private void sendMessage() {
        String message = inputField.getText().trim();
        if (message.isEmpty()) {
            return;
        }
        
        if (!isConnected || client == null) {
            showMessage("未连接到服务器", "错误");
            return;
        }
        
        client.sendMessage(message);
        showMessage(message, "已发送");
        inputField.clear();
    }
    
    private void handleReceivedMessage(String message) {
        String[] parts = message.split("\\|", 2);
        if (parts.length == 2) {
            String type = parts[0];
            String content = parts[1];
            showMessage(content, type);
        } else {
            showMessage(message, "已接收");
        }
    }
    
    private void handleStatusMessage(String status) {
        showMessage(status, "系统");
        
        if (status.contains("断开") || status.contains("错误") || status.contains("Disconnected") || status.contains("Error")) {
            resetConnectionState();
        }
    }
    
    public void showMessage(String message, String type) {
        Platform.runLater(() -> {
            String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("HH:mm:ss"));
            String formattedMessage = String.format("[%s] %s: %s\n", timestamp, type, message);
            messageArea.appendText(formattedMessage);
        });
    }
    
    public static void main(String[] args) {
        launch(args);
    }
}